import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler

# 加载日志数据
log_data = pd.read_csv('data.csv')

# 计算每对源IP和目的IP的连接次数
connection_counts = log_data.groupby(['src_ip', 'dst_ip', 'dst_port']).size().reset_index(name='count')

# 标准化连接次数特征数据
scaler = StandardScaler()
scaled_counts = scaler.fit_transform(connection_counts[['count']])

# 调用聚类算法（这里使用K均值聚类，请根据需要选择合适的聚类算法）
k = 8
kmeans = KMeans(n_clusters=k, random_state=0, n_init='auto')
kmeans.fit(scaled_counts)
labels = kmeans.labels_
# print(labels)
cluster_centers = kmeans.cluster_centers_
# print(cluster_centers)
result = connection_counts
result['label'] = pd.DataFrame(labels)
print(result)
result.to_csv("kmeans.csv", encoding = 'utf-8')